import subprocess
import pyotp
import pytest
import win32con
import win32gui
from airtest.aircv import *
from airtest.core.api import *
import logging
import random
import string
import allure


logger = logging.getLogger("airtest")
logger.setLevel(logging.ERROR)


class BasePage:
    def __init__(self):
        self.device = None

    #连接测试窗口，如果连接失败则启动测试程序
    def setup(self, device_path: str = "Windows:///?title_re=.*Cregis.*"):
        try:
            auto_setup(__file__, devices=[device_path])
            self.device = device()
            sleep(1)
            print("测试开始")
        except Exception as e:
            print(f"连接设备失败：{str(e)}")
            print("尝试启动该程序...")
            sleep(1)
            program_path = r"D:\w\UdunDev\UdunDev.exe"
            os.startfile(program_path)
            sleep(5)
            auto_setup(__file__, devices=[device_path])
            self.device = device()
            sleep(1)
            print("测试开始")


    def teardown(self):
        # snapshot(msg="结束测试")
        print("测试结束")


    def touch_element(self, template, delay: float = 1.0, desc: str = ""):
        # 点击操作
        try:
            touch(template)
            if desc:
                print(f"点击元素：{desc}")
            sleep(delay)
        except Exception as e:
            print(f"点击元素失败（{desc}）：{str(e)}")
            raise


    def input_text(self, content: str, delay: float = 1.0, desc: str = ""):
        #输入操作
        try:
            text(content)  # 这里调用Airtest的text()函数，参数为content
            if desc:
                print(f"输入文本：{content}（{desc}）")
            sleep(delay)
        except Exception as e:
            print(f"输入失败（{desc}）：{str(e)}")
            raise


    def random_name(self,length: int) -> str:
        # 生成随机字符串（大小写字母 + 数字）
        characters = string.ascii_letters + string.digits  # 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
        # 从字符集中随机选择length个字符，拼接成字符串
        random_str = ''.join(random.choice(characters) for i in range(length))
        return random_str


    def wait_element(self, template, timeout: float = 10.0, desc: str = ""):
        # 等待元素出现
        try:
            wait(template, timeout=timeout)
            if desc:
                print(f"元素出现：{desc}")
        except Exception as e:
            print(f"等待元素超时（{desc}，{timeout}s）：{str(e)}")
            raise


    def GetGoogleCode(self):
        #获取谷歌验证码并根据元素检测结果决定是否继续输入
        google_2fa_secret = "PU5LFBEGW2TPSGL6"  #MR77D6LAE33BDBT2
        totp = pyotp.TOTP(google_2fa_secret)
        while True:
            # 获取当前有效的谷歌验证码
            current_code = totp.now()
            # 输入验证码
            self.input_text(current_code)
            # 检测目标元素是否存在
            target_element_exists = Template(r"D:\AIRtest\UDun_UI\index\144820.png")
            # 如果元素不存在，结束循环；如果存在，继续获取新的验证码并输入
            if not target_element_exists:
                break


    def get_hwnd(self):
        # 获取当前窗口句柄
        hwnd = win32gui.FindWindow(None, "Cregis")
        return hwnd
    def move_window(self,get_hwnd,x,y,width,height):
        #移动窗口并修改窗口尺寸
        win32gui.SetWindowPos(get_hwnd, 0, x, y, width, height, win32con.SWP_NOZORDER)
        # SWP_NOMOVE保持窗口位置不变,SWP_NOSIZE #保持窗口大小不变,SWP_NOZORDER #保持窗口 Z 序（层级）不变


    def snap_shot(self , left_x,left_y,right_x,right_y):
        #截图
        img = self.device.snapshot()
        sna = crop_image(img, (left_x,left_y,right_x,right_y))
        save_path = "D:/AIRtest/UDun_UI/snapshot/Mnemonic_phrase.png"
        imwrite(save_path, sna)


    def extract_content(self):
        #提取文字内容
        pass

